<template>
    <div class="uploadImg">
        <div>
            <p>请添加图片...</p>
            <van-uploader v-model="fileList" :before-read="beforeRead" :after-read="afterRead" />
        </div>
        <img ref="uploadImg" v-for="(img, index) in hasCompressImg" :src="img" :key="index" alt="" style="width: 100%">
    </div>
</template>

<script>
    import {compression} from './js/compression'
    import {
        Uploader,
        Button,
        Tabbar,
        Toast
    } from 'vant'
    import 'vant/lib/button/style';
    import 'vant/lib/uploader/style';
    import 'vant/lib/tabbar/style';
    import 'vant/lib/toast/style';

    export default {
        name: "uploadImg",
        components: {
            [Uploader.name]: Uploader,
            [Button.name]: Button,
            [Tabbar.name]: Tabbar,
            [Toast.name]: Toast,
        },
        data () {
            return {
                fileList: [],
                hasCompressImg: []
            }
        },
        methods: {
            beforeRead (file) {
                const maxImgSize = 1024 * 1024 * 8 // 最大不要超过8M
                const imgSize = file.size
                if (imgSize > maxImgSize) {
                    Toast('上传图片不能超过8M')
                    return false
                }
                if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
                    Toast('请上传 jpg/png 格式图片')
                    return false
                }
                return true
            },
            async afterRead ({file, content}) {
                this.hasCompressImg = []
                const compressionFunc = await compression(file, content)
                // 如果不需要压缩图片 则compressionFunc 返回 false， 此时应该直接push content
                this.hasCompressImg.push(compressionFunc || content)
            }
        }
    }
</script>

<style scoped>
    .uploadImg {
        padding: 15px 15px 0 15px;
    }

    button {
        display: block;
        width: 100%
    }
</style>
